package cn.virens.common.project.generator.database.abstr;

import cn.virens.common.project.generator.database.config.GlobalConfig;
import cn.virens.common.project.generator.database.datasource.info.FieldInfo;
import cn.virens.common.project.generator.database.datasource.info.TableInfo;
import cn.virens.common.util.exception.APIException;
import cn.virens.common.util.exception.ExceptionUtil;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.dromara.hutool.core.io.file.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.util.List;

public abstract class AbstractGeneratorFileOut {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected final GlobalConfig globalConfig;

    protected final GroupTemplate template;

    protected final String templatePath;

    protected AbstractGeneratorFileOut(AbstractGenerator generator, String templatePath) {
        this.globalConfig = generator.globalConfig;
        this.template = generator.template;
        this.templatePath = templatePath;
    }

    /**
     * 文件渲染接口
     */
    public final String render(TableInfo table, List<FieldInfo> fields) throws APIException {
        return ExceptionUtil.e1(() -> render(output(table), table, fields));
    }

    private String render(String path, TableInfo table, List<FieldInfo> fields) throws Exception {
        logger.debug("正在生成({}):{}->{}", table.getName(), templatePath, path);

        try (OutputStream stream = FileUtil.getOutputStream(path)) {
            // 获取模版 & 绑定参数
            Template templ = template.getTemplate(templatePath);
            templ.binding("global", globalConfig);
            templ.binding("fields", fields);
            templ.binding("table", table);

            // 渲染内容
            templ.renderTo(stream);
        }

        return path;
    }

    protected String getStr(String key) {
        return globalConfig.getStr(key);
    }

    protected boolean getBool(String key) {
        return globalConfig.getBool(key);
    }

    /**
     * 获取顶层项目目录(按需调整)
     */
    protected String getRootPath() throws APIException {
        return System.getProperty("user.dir");
    }

    /**
     * 是否使用当前接口
     */
    protected abstract boolean enable() throws APIException;

    /**
     * 构建文件输出路径
     */
    protected abstract String output(TableInfo table) throws APIException;

}
